package com.oncliedisk.administrator.utils;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import com.oncliedisk.administrator.model.FileTaskModel;
import com.vdisk.android.VDiskAuthSession;
import com.vdisk.net.ProgressListener;
import com.vdisk.net.VDiskAPI;
import com.vdisk.net.exception.VDiskException;
import com.vdisk.net.exception.VDiskPartialFileException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DownFile extends AsyncTask<Object, Long, Boolean> {

    private Context context; //上下文
    VDiskAPI<VDiskAuthSession> mApi; //
    private String errorInfo; //错误信息
    private long fileLenght; //文件总字节数
    private VDiskAPI.VDiskFileInfo info;
    public FileTaskModel model;
    private com.oncliedisk.administrator.interfaces.onDownFileListener onDownFileListener;
    public static final String DOWNLOAD_TEMP_FILE_SUFFIX = ".vdisktemp";
    private  boolean isCancel; //是否停止
    private  FileOutputStream fos = null;
    private VDiskAPI.Entry metadata;

    public DownFile(Context context, FileTaskModel model, VDiskAPI<VDiskAuthSession> mApi, com.oncliedisk.administrator.interfaces.onDownFileListener onDownFileListener) {
        super();
        isCancel = false;
        this.context = context;
        this.model = model;
        this.mApi = mApi;
        this.onDownFileListener = onDownFileListener;
    }

    @Override
    protected Boolean doInBackground(Object... params) {
        Log.i("info","线程开启");
        if(isCancel == true){
            errorInfo = "暂停";
            return false;
        }
        String targetPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/VDisk_SDK_cache/" + model.getPath();
        File downloadDirFile = mApi.createDownloadDirFile(targetPath);
        try {
            fos = new FileOutputStream(downloadDirFile, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            errorInfo = "文件路径出错";
            return false;
        }

        try {
            info = mApi.getFile(model.getPath(), null, fos, downloadDirFile, new ProgressListener() {

                @Override
                public long progressInterval() {
                    return super.progressInterval();
                }

                @Override
                public void onProgress(long bytes, long total) {
                    //下载的实时进度
                    fileLenght = total;
                    publishProgress(bytes);
                }
            });
            if(isCancel == true){
                errorInfo = "暂停";
                return false;
            }
        } catch (VDiskPartialFileException e){
            errorInfo = "停止异常";
            return  false;
        }
        catch (VDiskException e) {
            e.printStackTrace();
            errorInfo = "下载问题";
            return false;
        }
        if (info != null) {
            metadata = info.getMetadata();
            return true;
        }
        return false;
    }

    public void setIsCancel(boolean isCancels){
        isCancel = isCancels;
    }

    @Override
    protected void onProgressUpdate(Long... progress) {
        int percent = (int) (100.0 * (double) progress[0] / fileLenght + 0.5);
        onDownFileListener.onProgress(percent, ExploerLoadSdFileTask.formateFileSize(progress[0]),model);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            onDownFileListener.onDownFinish(model,metadata);
        } else {
            onDownFileListener.onDownFail(errorInfo);
        }
    }

    public void closeThead(){
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
        isCancel = true;
    }

}